﻿/**
 * 
 *    Libero API for Fusion Charts to Asp.Net (Webforms & MVC)
 *    by: Roberto Barbedo (November, 2010) 
 *    email: r_barbedo@yahoo.com.br
 * 
 **/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Reflection;
using Libero.FusionCharts.Abstract;
using Libero.FusionCharts.Template;

namespace Libero.FusionCharts.Control
{
    [ToolboxData("<{0}:FChart runat=server></{0}:FChart>")]
    [System.Drawing.ToolboxBitmap(typeof(FChart), "Images.icon_chart.gif")]
    public class FChart : WebControl
    {
        /// <summary>
        /// Chart type. String, check docs to see available charts.
        /// </summary>
        [Bindable(true)]
        [DefaultValue("")]
        [Localizable(true)]
        public string ChartType
        {
            get
            {
                String s = (String)ViewState["ChartType"];
                return ((s == null) ? "" : s);
            }

            set
            {
                ViewState["ChartType"] = value;
            }
        }

        /// <summary>
        /// Charts data. XML, schema provided by fusioncharts.com/free
        /// </summary>
        [Bindable(true)]
        [DefaultValue("")]
        [Localizable(true)]
        public string XMLText
        {
            get
            {
                String s = (String)ViewState["XMLText"];
                return ((s == null) ? "" : s);
            }

            set
            {
                ViewState["XMLText"] = value;
            }
        }

        /// <summary>
        /// Bind a FusionChart with the WebControl FChart.
        /// </summary>
        /// <param name="chart"></param>
        public void ShowChart(FusionChartBase chart)
        {
            this.ChartType = chart.ChartType;
            this.XMLText = chart.ToXML();
        }

        /// <summary>
        /// On Init - Override apply JavaScript
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!this.Visible || !this.Enabled)
                return;

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("_lib_fc_js"))
            {
                string jsFunctions = Page.ClientScript.GetWebResourceUrl(typeof(FChart), "Libero.FusionCharts.Control.JavaScript.FusionCharts.js");
                Page.ClientScript.RegisterClientScriptInclude("_lib_fc_js", jsFunctions);
            }
            if (!Page.ClientScript.IsClientScriptBlockRegistered("_lib_get_res"))
            {
                Page.ClientScript.RegisterClientScriptBlock(typeof(FChart), "_lib_get_res", GetJsFunctionForResources(), true);
            }
        }

        /// <summary>
        ///  Renders the contents of the control to the specified writer. This method
        ///  is used primarily by control developers.
        /// </summary>
        /// <param name="output">A System.Web.UI.HtmlTextWriter that represents the output stream to render HTML content on the client.</param>
        protected override void RenderContents(HtmlTextWriter output)
        {
            if (!this.Visible || !this.Enabled)
                return;

            String sControlId = base.ClientID;
            String sJsVarId = "_lib_JS_" + base.ClientID;
            String sDivId = "_lib_DIV_" + base.ClientID;
            String sObjId = "_lib_OBJ_" + base.ClientID;
            String sWidth = "300";
            String sHeight = "250";

            if (Width.Value > 0)
                sWidth = Width.Value.ToString();
            if (Height.Value > 0)
                sHeight = Height.Value.ToString();

            StringBuilder oBuilder = new StringBuilder();

            oBuilder.AppendLine(@"<div id=""" + sDivId + @""" align=""center""></div>");

            oBuilder.AppendLine(@"<script type=""text/javascript"">");

            oBuilder.AppendLine(@"var " + sControlId + @" = (function() {");
            oBuilder.AppendLine(@"    return {");
            oBuilder.AppendLine(@"        containerId: '" + sDivId + "',");
            oBuilder.AppendLine(@"        xmlData: '',");
            oBuilder.AppendLine(@"        chartType: '',");
            oBuilder.AppendLine(@"        showChart: function() {");
            oBuilder.AppendLine(@"            var " + sJsVarId + @" = new FusionCharts(_lib_gR(this.chartType), """ + sObjId + @""", """ + sWidth + @""", """ + sHeight + @""");");
            oBuilder.AppendLine(@"            " + sJsVarId + @".setDataXML(this.xmlData);");
            oBuilder.AppendLine(@"            " + sJsVarId + @".render(""" + sDivId + @""");");
            oBuilder.AppendLine(@"        }");
            oBuilder.AppendLine(@"    }");
            oBuilder.AppendLine(@"})();");

            oBuilder.AppendLine(@"setTimeout(function(){");
            oBuilder.AppendLine(@"    " + sControlId + @".xmlData = """ + XMLText.Replace(@"""", @"'") + @""";");
            oBuilder.AppendLine(@"    " + sControlId + @".chartType = """ + this.ChartType + @""";");
            oBuilder.AppendLine(@"    " + sControlId + @".showChart();");
            oBuilder.AppendLine(@"},0);");

            oBuilder.AppendLine(@"</script>");

            output.Write(oBuilder.ToString());
        }

        #region [ SWF Resources ]
        private string GetJsFunctionForResources()
        {
            StringBuilder oBuilder = new StringBuilder();

            oBuilder.AppendLine(@"_lib_gR = function(chart){");
            foreach (string key in SWFDictionary.Keys)
            {
                oBuilder.AppendLine(@"if(chart=='" + key + @"')");
                oBuilder.Append(@"{return'" + SWFDictionary[key] + @"';}");
            }
            oBuilder.AppendLine(@"}");

            return oBuilder.ToString();
        }
        private Dictionary<string, string> _SWFDictionary;
        private Dictionary<string, string> SWFDictionary
        {
            get
            {
                if (_SWFDictionary == null)
                {
                    _SWFDictionary = new Dictionary<string, string>();
                    _SWFDictionary.Add("Area2DChart", getUrl("FCF_Area2D.swf"));
                    _SWFDictionary.Add("Bar2DChart", getUrl("FCF_Bar2D.swf"));
                    _SWFDictionary.Add("CandlestickChart", getUrl("FCF_Candlestick.swf"));
                    _SWFDictionary.Add("Column2DChart", getUrl("FCF_Column2D.swf"));
                    _SWFDictionary.Add("Column3DChart", getUrl("FCF_Column3D.swf"));
                    _SWFDictionary.Add("Doughnut2DChart", getUrl("FCF_Doughnut2D.swf"));
                    _SWFDictionary.Add("FunnelChart", getUrl("FCF_Funnel.swf"));
                    _SWFDictionary.Add("GanttChart", getUrl("FCF_Gantt.swf"));
                    _SWFDictionary.Add("LineChart", getUrl("FCF_Line.swf"));
                    _SWFDictionary.Add("MSArea2DChart", getUrl("FCF_MSArea2D.swf"));
                    _SWFDictionary.Add("MSBar2DChart", getUrl("FCF_MSBar2D.swf"));
                    _SWFDictionary.Add("MSColumn2DChart", getUrl("FCF_MSColumn2D.swf"));
                    _SWFDictionary.Add("MSColumn2DLineDYChart", getUrl("FCF_MSColumn2DLineDY.swf"));
                    _SWFDictionary.Add("MSColumn3DChart", getUrl("FCF_MSColumn3D.swf"));
                    _SWFDictionary.Add("MSColumn3DLineDYChart", getUrl("FCF_MSColumn3DLineDY.swf"));
                    _SWFDictionary.Add("MSLineChart", getUrl("FCF_MSLine.swf"));
                    _SWFDictionary.Add("Pie2DChart", getUrl("FCF_Pie2D.swf"));
                    _SWFDictionary.Add("Pie3DChart", getUrl("FCF_Pie3D.swf"));
                    _SWFDictionary.Add("StackedArea2DChart", getUrl("FCF_StackedArea2D.swf"));
                    _SWFDictionary.Add("StackedBar2DChart", getUrl("FCF_StackedBar2D.swf"));
                    _SWFDictionary.Add("StackedColumn2DChart", getUrl("FCF_StackedColumn2D.swf"));
                    _SWFDictionary.Add("StackedColumn3DChart", getUrl("FCF_StackedColumn3D.swf"));
                }
                return _SWFDictionary;
            }
            set { _SWFDictionary = value; }
        }
        private string getUrl(string swf)
        {
            return Page.ClientScript.GetWebResourceUrl(typeof(FChart), "Libero.FusionCharts.Control.FusionChartsFiles." + swf);
        }
        #endregion
    }
}

